﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;
using ComponentFactory.Krypton.Toolkit;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Helpers;
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;

    public partial class ProductForm : Form
    {
        /// <summary>
        /// All columns in the grid
        /// </summary>
        private class ColumnIndex
        {
            public const int Id = 0;
            public const int Name = 1;
            public const int Cost = 2;
            public const int Price = 3;
        }

        private static readonly ILogger _logger = Program.Logger.CreateChildLogger("ProductForm");
        private IRepository<Product> productRepository = null;
        private IList<Product> listOfProducts = null;
        private IList<Product> listOfProductsToDelete = null;

        #region Constructors

        public ProductForm()
        {
            InitializeComponent();

            this.SetUp();
            this.LoadData();
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Setup the data grid
        /// </summary>
        private void SetUp()
        {
            this.productRepository = Program.Container.Resolve<IRepository<Product>>();

            this.kdgvProducts.AutoGenerateColumns = false;
            var idColumn = new DataGridViewColumn
            {
                DataPropertyName = Product.Properties.Id,
                Name = Product.Properties.Id,
                HeaderText = "Id",
                ValueType = typeof(int),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = false
            };
            this.kdgvProducts.Columns.Add(idColumn);

            var nameColumn = new DataGridViewColumn
            {
                DataPropertyName = Product.Properties.Name,
                Name = Product.Properties.Name,
                HeaderText = "Name",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true,
                MinimumWidth = 200,
            };
            this.kdgvProducts.Columns.Add(nameColumn);

            var costColumn = new DataGridViewColumn
            {
                DataPropertyName = Product.Properties.Cost,
                Name = Product.Properties.Cost,
                HeaderText = "Cost",
                ValueType = typeof(decimal),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true
            };
            this.kdgvProducts.Columns.Add(costColumn);

            var priceColumn = new DataGridViewColumn
            {
                DataPropertyName = Product.Properties.Price,
                Name = Product.Properties.Price,
                HeaderText = "Price",
                ValueType = typeof(decimal),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true
            };
            this.kdgvProducts.Columns.Add(priceColumn);
        }

        /// <summary>
        /// Load all accounts from database
        /// </summary>
        private void LoadData()
        {
            this.listOfProducts = this.productRepository.FindAll();
            if (this.listOfProducts == null)
            {
                this.listOfProducts = new List<Product>();
            }

            foreach (Product productItem in this.listOfProducts)
            {
                this.DisplayProductData(productItem);
            }
        }

        private void DisplayProductData(Product productItem)
        {
            if (productItem != null)
            {
                this.kdgvProducts.Rows.Add(productItem.Id, productItem.Name, productItem.Cost, productItem.Price);
            }
        }

        private void UpdateProductData(Product productItem)
        {
            if (productItem != null)
            {
                foreach (DataGridViewRow rowItem in this.kdgvProducts.Rows)
                {
                    if (productItem.Id.Equals(rowItem.Cells[ColumnIndex.Id].Value))
                    {
                        rowItem.Cells[ColumnIndex.Name].Value = productItem.Name;
                        rowItem.Cells[ColumnIndex.Cost].Value = productItem.Cost;
                        rowItem.Cells[ColumnIndex.Price].Value = productItem.Price;

                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Add new account into the list and data grid
        /// </summary>
        /// <param name="account"></param>
        private void AddOrUpdateProduct(Product productItem)
        {
            if (productItem != null)
            {
                Product existingProduct = this.listOfProducts.FirstOrDefault(item => (item.Id == productItem.Id));
                if (existingProduct == null)
                {
                    this.listOfProducts.Add(productItem);
                    this.DisplayProductData(productItem);
                }
                else
                {
                    existingProduct = productItem;
                    this.UpdateProductData(productItem);
                }
            }
        }

        private void ShowAccountForm(DataGridViewRow rowItem)
        {
            if (rowItem != null)
            {
                int productId = Convert.ToInt32(rowItem.Cells[ColumnIndex.Id].Value);
                Product productItem = this.listOfProducts.FirstOrDefault(item => (item.Id == productId));
                using (ProductEditForm productForm = new ProductEditForm(productItem)
                {
                    StartPosition = FormStartPosition.CenterParent
                })
                {
                    var result = productForm.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        this.AddOrUpdateProduct(productForm.SelectedProduct);
                    }
                }
            }
        }

        private DialogResult ConfirmRemoveProducts()
        {
            var result = DialogResult.None;

            if (this.kdgvProducts.SelectedRows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Are you sure you want to delete these product:");
                sb.AppendLine();
                foreach (DataGridViewRow rowItem in this.kdgvProducts.SelectedRows)
                {
                    sb.AppendFormat("   {0}", rowItem.Cells[ColumnIndex.Name].Value);
                    sb.AppendLine();
                }

                result = KryptonMessageBox.Show(sb.ToString(), "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            }

            return result;
        }

        /// <summary>
        /// Detects has changes on products or not.
        /// </summary>
        /// <returns></returns>
        private bool HasChanged()
        {
            bool result = false;
            if ((this.listOfProductsToDelete != null) && (this.listOfProductsToDelete.Count > 0))
            {
                result = true;
            }
            else if (this.listOfProducts != null)
            {
                if (this.listOfProducts.FirstOrDefault(productItem => (productItem.Id < 0)) != null)
                {
                    result = true;
                }
                else
                {
                }
            }

            return result;
        }

        private void SaveChanges()
        {
            if (this.listOfProductsToDelete != null)
            {
                foreach (Product productItem in this.listOfProductsToDelete)
                {
                    if (productItem != null)
                    {
                        productItem.Delete();
                    }
                }
            }

            if (this.listOfProducts != null)
            {
                foreach (Product productItem in this.listOfProducts)
                {
                    productItem.Save();
                }
            }
        }

        #endregion

        #region Events

        private void btnNewProduct_Click(object sender, EventArgs e)
        {
            using (ProductEditForm productForm = new ProductEditForm()
            {
                StartPosition = FormStartPosition.CenterParent
            })
            {
                var result = productForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.AddOrUpdateProduct(productForm.SelectedProduct);
                }
            }
        }

        private void btnSaveChanges_Click(object sender, EventArgs e)
        {
            try
            {
                this.SaveChanges();

                this.DialogResult = DialogResult.OK;
                this.Close();
                this.Dispose();

                GC.SuppressFinalize(this);
            }
            catch (Exception ex)
            {
                this.DialogResult = DialogResult.No;
                _logger.Error("Error while saving changes", ex);
            }
        }

        private void kdgvProducts_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                default:
                    break;
            }
        }

        private void kdgvProducts_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataGridViewCell modifiedCell = this.kdgvProducts.Rows[e.RowIndex].Cells[e.ColumnIndex];

                int productId = Convert.ToInt32(this.kdgvProducts.Rows[e.RowIndex].Cells[ColumnIndex.Id].Value);
                Product selectedProduct = this.listOfProducts.FirstOrDefault(item => (item.Id == productId));

                switch (e.ColumnIndex)
                {
                    case ColumnIndex.Name:
                        selectedProduct.Name = Convert.ToString(modifiedCell.Value);
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat(ex, "Error while editing cell: {0}", e.ColumnIndex);
            }
        }

        private void kdgvProducts_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            int productId = Convert.ToInt32(e.Row.Cells[ColumnIndex.Id].Value);
            Product productItem = this.listOfProducts.FirstOrDefault(item => (item.Id == productId));

            if (this.listOfProductsToDelete == null)
            {
                this.listOfProductsToDelete = new List<Product>();
            }
            this.listOfProductsToDelete.Add(productItem);
            this.listOfProducts.Remove(productItem);
        }

        private void kdgvProducts_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (this.ConfirmRemoveProducts() != DialogResult.Yes)
            {
                e.Cancel = true;
            }
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.kdgvProducts.CurrentRow != null)
                {
                    this.ShowAccountForm(this.kdgvProducts.CurrentRow);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error while updating account", ex);
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ConfirmRemoveProducts() == DialogResult.Yes)
            {
                foreach (DataGridViewRow rowItem in this.kdgvProducts.SelectedRows)
                {
                    this.kdgvProducts.Rows.Remove(rowItem);

                    // Add deleted rows into the list
                    int productId = Convert.ToInt32(rowItem.Cells[ColumnIndex.Id].Value);
                    Product accountItem = this.listOfProducts.FirstOrDefault(item => (item.Id == productId));

                    if (this.listOfProductsToDelete == null)
                    {
                        this.listOfProductsToDelete = new List<Product>();
                    }
                    this.listOfProductsToDelete.Add(accountItem);
                    this.listOfProducts.Remove(accountItem);
                }
            }
        }

        private void ProductForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.HasChanged())
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("There is some changes on products. Do you want to save these changes?");

                DialogResult result = KryptonMessageBox.Show(sb.ToString(), "Confirmation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                switch (result)
                {
                    case DialogResult.Yes:
                        try
                        {
                            this.SaveChanges();

                            this.Close();
                            this.Dispose();

                            GC.SuppressFinalize(this);
                        }
                        catch (Exception ex)
                        {
                            this.DialogResult = DialogResult.No;
                            _logger.Error("Error while saving changes", ex);
                        }
                        break;

                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;
                }
            }
        }

        #endregion

    }
}